<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入所属公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="carNo">
        <el-input
          v-model="queryParams.carNo"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户号" prop="merchantId">
        <el-input
          v-model="queryParams.merchantId"
          placeholder="请输入商户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:driver_car:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:driver_car:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:driver_car:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:driver_car:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-picture"
          size="mini"
          @click="handleExportAllQRCode"
          v-hasPermi="['system:driver_car:qrcode']"
        >导出全部二维码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:driver_car:import']"
        >导入司机信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="downloadTemplate"
           v-hasPermi="['system:driver_car:import']"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImportAvatar"
           v-hasPermi="['system:driver_car:import']"
        >导入司机头像</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="driver_carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号"  align="center" prop="id" width="80" />
      <el-table-column label="姓名" align="center" prop="name" width="80" />
      <el-table-column label="用户性别" align="center" prop="sex" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="phone" width="120" />
      <el-table-column label="司机评分" align="center" prop="evaluate" width="80" />
      <el-table-column label="所属公司" align="center" prop="company" width="300" />
      <el-table-column label="车牌号" align="center" prop="carNo" width="120" />
      <el-table-column label="商户号" align="center" prop="merchantId" width="250" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:driver_car:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:driver_car:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-picture"
            @click="handleGenerateQRCode(scope.row)"
            v-hasPermi="['system:driver_car:qrcode']"
          >查看收款码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改司机车辆信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择用户性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="司机评分" prop="evaluate">
          <el-input v-model="form.evaluate" placeholder="请输入司机评分" />
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="form.company" placeholder="请输入所属公司" />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNo">
          <el-input v-model="form.carNo" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="商户号" prop="merchantId">
          <el-input v-model="form.merchantId" placeholder="请输入商户号" />
        </el-form-item>
        <el-form-item label="司机头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :http-request="customUpload"
            :show-file-list="false"
          >
            <img v-if="form.avatar" :src="'https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/' + form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 司机详情对话框 -->
    <el-dialog title="司机详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="司机头像">
          <el-image
            v-if="detailForm.avatar"
            style="width: 100px; height: 100px"
            :src="'https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/' + detailForm.avatar"
            :preview-src-list="['https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/' + detailForm.avatar]">
          </el-image>
          <span v-else>暂无头像</span>
        </el-descriptions-item>
        <el-descriptions-item label="姓名">{{ detailForm.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <dict-tag :options="dict.type.sys_user_sex" :value="detailForm.sex"/>
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ detailForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="司机评分">{{ detailForm.evaluate }}</el-descriptions-item>
        <el-descriptions-item label="所属公司">{{ detailForm.company }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ detailForm.carNo }}</el-descriptions-item>
        <el-descriptions-item label="商户号">{{ detailForm.merchantId }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入司机头像对话框 -->
    <el-dialog :title="avatarUpload.title" :visible.sync="avatarUpload.open" width="600px" append-to-body>
      <el-form ref="avatarForm" :model="avatarForm" :rules="avatarRules" label-width="100px">
        <el-form-item label="所属公司" prop="company">
          <el-select v-model="avatarForm.company" placeholder="请选择所属公司">
            <el-option
              v-for="item in companyOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像压缩包" prop="file">
          <el-upload
            ref="avatarUpload"
            :limit="1"
            accept=".zip"
            :headers="avatarUpload.headers"
            :action="avatarUpload.url"
            :disabled="avatarUpload.isUploading"
            :on-progress="handleAvatarUploadProgress"
            :on-success="handleAvatarSuccess"
            :auto-upload="false"
            :on-change="handleAvatarChange"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入zip格式的压缩包。</span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAvatarForm">确 定</el-button>
        <el-button @click="avatarUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDriver_car, getDriver_car, delDriver_car, addDriver_car, updateDriver_car, generateDriverQRCode } from "@/api/system/driver_car";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";
import { uploadToCOS } from "@/api/passenger/upload";

export default {
  name: "Driver_car",
  dicts: ['sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 司机车辆信息表格数据
      driver_carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示导入弹出层
      importOpen: false,
      // 导入选项
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/api/driver/importTemplateFile"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sex: null,
        phone: null,
        company: null,
        carNo: null,
        merchantId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        carNo: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ]
      },
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情表单参数
      detailForm: {},
      // 导入头像选项
      avatarUpload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "导入司机头像",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/api/driver/importAvatar"
      },
      // 公司选项
      companyOptions: [
        "酒泉丝路宏途交通建设发展有限责任公司",
        "交运出租",
        "酒泉亚飞永盛旅游汽车出租有限公司"
      ],
      // 头像表单参数
      avatarForm: {
        company: undefined,
        file: undefined
      },
      // 头像表单校验
      avatarRules: {
        company: [
          { required: true, message: "请选择所属公司", trigger: "change" }
        ],
        file: [
          { required: true, message: "请选择头像压缩包", trigger: "change" }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询司机车辆信息列表 */
    getList() {
      this.loading = true;
      listDriver_car(this.queryParams).then(response => {
        this.driver_carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sex: null,
        phone: null,
        evaluate: null,
        company: null,
        carNo: null,
        merchantId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加司机车辆信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDriver_car(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改司机车辆信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDriver_car(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDriver_car(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除司机车辆信息编号为"' + ids + '"的数据项？').then(function() {
        return delDriver_car(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/driver_car/export', {
        ...this.queryParams
      }, `driver_car_${new Date().getTime()}.xlsx`)
    },
    /** 导出全部二维码操作 */
    handleExportAllQRCode() {
      const loading = this.$loading({
        lock: true,
        text: '正在生成二维码，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 如果有选中的行，则传递选中的id
      const params = {
        company: this.queryParams.company,
        ids: this.ids.length > 0 ? this.ids.join(',') : undefined
      };

      generateDriverQRCode(params, {
        responseType: 'blob',
        timeout: 300000  // 设置5分钟超时（300000毫秒）
      }).then(response => {
        // 创建一个 Blob 对象
        const blob = new Blob([response], { type: 'application/zip' });
        // 创建一个下载链接
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'qrcodes.zip';
        // 触发下载
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
        loading.close();
        this.$modal.msgSuccess("二维码导出成功");
      }).catch(() => {
        loading.close();
        this.$modal.msgError("二维码导出失败");
      });
    },
    /** 生成收款码操作 */
    handleGenerateQRCode(row) {
      const id = row.id;
      if (!row.merchantId) {
        this.$modal.msgError("商户号为空，无法生成收款码");
        return;
      }
      generateDriverQRCode({id:id, company: row.company}, { responseType: 'blob' }).then(response => {
        // 创建一个 Blob 对象
        const blob = new Blob([response], { type: 'application/zip' });
        // 创建一个下载链接
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'qrcodes.zip';
        // 触发下载
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
        this.$modal.msgSuccess("收款码生成成功");
      }).catch(() => {
        this.$modal.msgError("收款码生成失败");
      });
    },
    /** 下载导入模板 */
    downloadTemplate() {
      window.location.href = "http://quansutong.quansuchong.com/front/file/template/driverCarInfo.xlsx";
    },
    /** 导入司机信息 */
    handleImport() {
      this.upload.title = "导入司机信息";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.downloadTemplate();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      const id = row.id || this.ids;
      getDriver_car(id).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 导入司机头像按钮操作 */
    handleImportAvatar() {
      this.avatarUpload.open = true;
      this.avatarForm = {
        company: undefined,
        file: undefined
      };
    },
    // 头像文件上传中处理
    handleAvatarUploadProgress(event, file, fileList) {
      this.avatarUpload.isUploading = true;
    },
    // 头像文件上传成功处理
    handleAvatarSuccess(response, file, fileList) {
      this.avatarUpload.open = false;
      this.avatarUpload.isUploading = false;
      this.$refs.avatarUpload.clearFiles();
      this.$modal.msgSuccess("导入成功");
      this.getList();
    },
    // 头像文件改变时处理
    handleAvatarChange(file, fileList) {
      this.avatarForm.file = fileList.length > 0 ? fileList[0] : undefined;
      this.$refs.avatarForm.validateField('file');
    },
    // 提交头像上传文件
    submitAvatarForm() {
      this.$refs["avatarForm"].validate(valid => {
        if (valid) {
          if (!this.$refs.avatarUpload.uploadFiles || this.$refs.avatarUpload.uploadFiles.length === 0) {
            this.$modal.msgError("请选择头像压缩包");
            return;
          }
          const formData = new FormData();
          formData.append('file', this.$refs.avatarUpload.uploadFiles[0].raw);
          formData.append('company', this.avatarForm.company);

          this.avatarUpload.isUploading = true;
          request({
            url: '/api/driver/importUserAvatar',
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response => {
            this.avatarUpload.open = false;
            this.avatarUpload.isUploading = false;
            this.$refs.avatarUpload.clearFiles();
            this.$modal.msgSuccess("导入成功");
            this.getList();
          }).catch(() => {
            this.avatarUpload.isUploading = false;
          });
        }
      });
    },
    // 自定义上传方法
    customUpload(event) {
      let file = event.file;
      if(file.size/1024 > 10*1024){
        this.$message.warning('单个文件大小不能超过10MB');
        return;
      }
      let data = new FormData();
      data.append('file', file);
      this.$modal.loading("正在上传头像，请稍候...");
      uploadToCOS(data).then(response => {
        this.$modal.closeLoading();
        if (response.code === 200) {
          this.form.avatar = response.data;
          this.$modal.msgSuccess("上传成功");
        } else {
          this.$modal.msgError("上传失败");
        }
      }).catch(() => {
        this.$modal.closeLoading();
        this.$modal.msgError("上传失败");
      });
    },
  }
};
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
